import { expect } from '@jest/globals';
import fsExtra from 'fs-extra';
import JSON5 from 'json5';
import path from 'path';

import { initExecuteCommand, runHvigorAsync } from '../../common/common';
import {
  AbilityType,
  APIType,
  APIVersion,
  CaseLevel,
  IsEnable,
  LanguageType,
  ModuleTemplateType,
  RuntimeOSType,
  SDKType,
  SignType
} from '../../plugins/project-builder/models/constants';
import { TestCaseBuilder } from '../../plugins/task-builder/task-case-builder';
import { ProjectBuildOption, TestCaseFun } from '../../plugins/task-builder/test-case';
import { TestTaskOption } from '../../plugins/task-builder/test-task-option';

const projectBuilderOption: ProjectBuildOption = {
  template: {
    sdk: SDKType.Single,
    runtimeOS: RuntimeOSType.HarmonyOS,
    apiVersion: APIVersion.API10,
    apiType: APIType.STAGE,
    language: LanguageType.ArkTs,
    abilityType: AbilityType.Application,
    entryTemplateType: ModuleTemplateType.EmptyAbility
  },
  modulesOption: {
    [ModuleTemplateType.EmptyAbility]: 1
  }
};

const taskConfig: TestTaskOption = {
  caseLevel: CaseLevel.L1,
  sign: SignType.NoSign,
  ohpmInstall: IsEnable.DisAble,
};

const testFun: TestCaseFun = async (project, taskConfig, record) => {
  const projectRootPath = project.projectRootPath();
  const commands = initExecuteCommand({
    mode: 'module',
    product: 'default',
    tasks: 'assembleHap'
  });

  // 删除 entry module.json5 文件的 pages
  const entryPath = project.getModule('entry').moduleRootPath();
  const entryBuffer = await fsExtra.readFile(`${entryPath}/src/main/module.json5`);
  const entryModuleJson5 = JSON5.parse(entryBuffer.toString());
  delete entryModuleJson5.module.pages;
  await fsExtra.writeFile(`${entryPath}/src/main/module.json5`, JSON5.stringify(entryModuleJson5));

  // 删除 feature module.json5 文件的 pages
  const applicationPath = project.getModule('application').moduleRootPath();
  const applicationBuffer = await fsExtra.readFile(`${applicationPath}/src/main/module.json5`);
  const applicationData = JSON5.parse(applicationBuffer.toString());
  delete applicationData.module.pages;
  await fsExtra.writeFile(path.resolve(applicationPath, 'src/main/module.json5'), JSON5.stringify(applicationData));

  // 构建hap包
  const result = await runHvigorAsync(projectRootPath, commands);
  record.addStep('删除完pages属性后执行hap编译构建', result);
  expect(result.stdout).toContain('Finished :application:default@PackageHap');
  expect(result.stdout).toContain('Finished :entry:default@PackageHap');
  expect(result.stdout).toContain('BUILD SUCCESSFUL');
};

TestCaseBuilder.builder()
  .caseName('OPEN_LAB_AIDE_ZOS_module_buildHap_HOS_API10_STAGE_024')
  .description('模块module.json5文件中删除pages配置编译')
  .projectBuilderOption(projectBuilderOption)
  .taskConfig(taskConfig)
  .testFun(testFun)
  .load();
